//
//  BabyInfoViewController.m
//  parent
//
//  Created by 闫珍 on 15/5/19.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "BabyInfoViewController.h"
#import "Utils.h"
#import "JsonUtil.h"
#import "NetWorkManager.h"
#import "PopUIManager.h"
#import "CameraGalleryManager.h"
#import "UserDao.h"
#import "JoinClassViewController.h"

@interface BabyInfoViewController ()<UIActionSheetDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *babyName;

@property (weak, nonatomic) IBOutlet UITextField *babyDate;

@property (weak, nonatomic) IBOutlet UITextField *babySex;
@property (nonatomic,copy) NSString *babyY;
@property (nonatomic,copy) NSString *babyM;
@property (nonatomic,copy) NSString *babyD;
@property (nonatomic,strong) NSArray *sexs;
@property NSUInteger babyS;
@property (nonatomic,copy) NSString *babyAvatar;
@property (weak, nonatomic) IBOutlet UIButton *babyBtn;

@end

@implementation BabyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    _sexs = @[@"男",@"女"];
    [self customView];
    
}

-(void)customView
{
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"填写宝贝资料";
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    self.navigationItem.rightBarButtonItem
    =[[UIBarButtonItem alloc]initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(nextStep:)];
    [Utils textFiled:_babyName padding:15];
    [Utils textFiled:_babyDate padding:15];
    [Utils textFiled:_babySex padding:15];
    
    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    [datePicker setMaximumDate:[NSDate date]];
    [datePicker setMinimumDate:[NSDate dateWithTimeIntervalSinceNow:-1 * 3600* 24 * 365 *20]];
    [datePicker setDate:[NSDate dateWithTimeIntervalSinceNow:-1 * 3600* 24 * 365*5]];
    datePicker.datePickerMode = UIDatePickerModeDate;
    [datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
    
    [_babyDate setInputView:datePicker];
    
    //设置默认值
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd"];
    _babyDate.text=[format stringFromDate:datePicker.date];
    [format setDateFormat:@"yyyy"];
    _babyY =[format stringFromDate:datePicker.date];
    [format setDateFormat:@"MM"];
    _babyM = [format stringFromDate:datePicker.date];
    [format setDateFormat:@"dd"];
    _babyD = [format stringFromDate:datePicker.date];
    
    
    
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    
    [pickerView sizeToFit];
    pickerView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.showsSelectionIndicator = YES;
    _babySex.inputView = pickerView;
    _babyS=1;
    _babySex.text = [_sexs objectAtIndex:0];
    
    [self.navigationController.navigationBar setBarTintColor:UIColorMake(252,74,74)];
    self.navigationController.navigationBar.shadowImage = nil;
    self.navigationController.navigationBar.translucent = NO;
    [self.view setBackgroundColor:DefaultViewColor];
}

#pragma mark ----------关于性别选择---------------
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [_sexs objectAtIndex:row];
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _sexs.count;
}
- (IBAction)birthDayClick:(id)sender {
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate *date =[NSDate dateWithTimeIntervalSinceNow:-1 * 3600* 24 * 365*5];
    _babyDate.text=[format stringFromDate:date];
    [format setDateFormat:@"yyyy"];
    _babyY =[format stringFromDate:date];
    [format setDateFormat:@"MM"];
    _babyM = [format stringFromDate:date];
    [format setDateFormat:@"dd"];
    _babyD = [format stringFromDate:date];

}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    debugLog(@"选择的性别是：%@",[_sexs objectAtIndex:row]);
    _babySex.text = [_sexs objectAtIndex:row];
    if (row == 0) {  //男
        [_babyBtn setImage:[UIImage imageNamed:@"default_avatar"] forState:UIControlStateNormal];
    }else{ //女
        [_babyBtn setImage:[UIImage imageNamed:@"default_avatar_girl"] forState:UIControlStateNormal];
    }
    
    _babyS = row +1;
}

#pragma mark ----------关于生日选择---------------

-(void)changeDate:(UIDatePicker *)picker
{
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd"];
    _babyDate.text=[format stringFromDate:picker.date];
    [format setDateFormat:@"yyyy"];
    _babyY =[format stringFromDate:picker.date];
    [format setDateFormat:@"MM"];
    _babyM = [format stringFromDate:picker.date];
    [format setDateFormat:@"dd"];
    _babyD = [format stringFromDate:picker.date];
}

- (IBAction)babyAvatar:(id)sender {
    
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册",nil];
    [sheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ((int)buttonIndex == 0) {  //拍照
        
        //延时0.3s调用相机
        [self performSelector:@selector(showCamera) withObject:nil afterDelay:0.3];
    }else if ((int)buttonIndex == 1){//相册
        
        [[CameraGalleryManager getInstanse] gallerySelect:self finishBlock:^(UIImage *img, NSString * avaURL) {
            
            [self.babyBtn setImage:img forState:UIControlStateNormal];
            _babyAvatar = avaURL;
        }];
    }else if ((int)buttonIndex == 2){//取消
        debugLog(@"取消");
    }
}

-(void) showCamera{
    [[CameraGalleryManager getInstanse] takePhoto:self finishBlock:^(UIImage *img, NSString * avaURL) {
        
        [self.babyBtn setImage:img forState:UIControlStateNormal];
        _babyAvatar = avaURL;
    }];
}


-(void)nextStep:(id)sender
{
    //注册开始
    if([_babyName.text isEqualToString:@""]){
        [[PopUIManager getInstanse]popAlertView:nil title:@"提示" message:@"宝贝名字不能为空" cancelButtonTitle:@"确定"];
        return;
    }
    if([_babyDate.text isEqualToString:@""]){
        [[PopUIManager getInstanse]popAlertView:nil title:@"提示" message:@"宝贝生日不能为空" cancelButtonTitle:@"确定"];
        return;
    }
    if([_babySex.text isEqualToString:@""]){
        [[PopUIManager getInstanse]popAlertView:nil title:@"提示" message:@"宝贝性别不能为空" cancelButtonTitle:@"确定"];
        return;
    }
    if(_add_baby){
        [self do_add];
    }else{
        [self registerMe];
    }
    
}

-(void)do_add
{
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@([[UserDao getInstance] getUserId]), @"uid",
                                 @(1),@"utype",
                                 [[UserDao getInstance]getAccessToken], @"token",
                                 nil];

    
    [dict setObject:_babyName.text forKey:@"baby_name"];
    if(_babyY.length>0){
        [dict setObject:_babyY forKey:@"baby_y"];
    }
    if(_babyM.length>0){
        [dict setObject:_babyM forKey:@"baby_m"];
    }
    if(_babyD.length>0){
        [dict setObject:_babyD forKey:@"baby_d"];
    }
    
    [dict setObject:@(_babyS) forKey:@"baby_s"];
    
    if(_babyAvatar.length>0){
        [dict setObject:_babyAvatar forKey:@"baby_avatar"];
    }
    
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:dict];
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_ADD_BABY data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [popUIMgr removeWaitingUI];
        if (connectionError) { //连接失败
            debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                debugLog(@"数据字典: %@", dict);
                
                if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                    NSString *ret_msg;
                    switch ([[dict objectForKey:@"retCode"] integerValue]) {
                        case 1:
                        {
                            ret_msg= @"Success";
                            break;
                        }
                        case 10005:{
                            ret_msg= @"宝宝无法插入";
                            break;
                        }
                        case 10012:{
                            ret_msg =@"家长不存在";
                            break;
                        }
                            
                    }
                    if (![ret_msg isEqual:@"Success"]) {
                        [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                        return;
                    }else{
                        //添加成功
                        debugLog(@"%@",dict);
                        //保存用户数据
                        
                        NSDictionary *babyinfo = [dict objectForKey:@"babyinfo"];
                        NSMutableDictionary *dicc = [[NSMutableDictionary alloc]initWithDictionary:babyinfo];
                        [dicc setObject:[babyinfo objectForKey:@"babyid"] forKey:@"id"];
                        BOOL result = [[BabyDao getInstance]saveBabyData:dicc];
                       
                        if(result){
                            JoinClassViewController *joinClass = [[JoinClassViewController alloc]init];
                            joinClass.babyid = [[babyinfo objectForKey:@"babyid"] integerValue];
                            [self.navigationController pushViewController:joinClass animated:YES];
                        }else{
                            [popUIMgr popAlertView:nil title:@"提示" message:@"添加宝贝失败" cancelButtonTitle:@"确定"];
                        }
                        
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                    return;
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                return;
            }
        }
        
    }];
}

-(void)registerMe
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:_phoneNum, @"phone",
                                 _password, @"pwd",
                                 _nickname, @"nickname",
                                 @(_frole), @"frole",
                                 nil];
    if(_avatar.length>0){
        [dict setObject:_avatar forKey:@"avatar"];
    }
    
    if(_babyName.text.length>0){
        [dict setObject:_babyName.text forKey:@"baby_name"];
        if(_babyY.length>0){
            [dict setObject:_babyY forKey:@"baby_y"];
        }
        if(_babyM.length>0){
            [dict setObject:_babyM forKey:@"baby_m"];
        }
        if(_babyD.length>0){
            [dict setObject:_babyD forKey:@"baby_d"];
        }
        
        [dict setObject:@(_babyS) forKey:@"baby_s"];
        
        if(_babyAvatar.length>0){
            [dict setObject:_babyAvatar forKey:@"baby_avatar"];
        }
    }
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:dict];
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_REGISTER data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [popUIMgr removeWaitingUI];
        if (connectionError) { //连接失败
            debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                debugLog(@"数据字典: %@", dict);
                
                if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                    NSString *ret_msg;
                    switch ([[dict objectForKey:@"retCode"] integerValue]) {
                        case 1:
                        {
                            ret_msg= @"Success";
                            break;
                        }
                        case 10005:{
                            ret_msg= @"注册失败";
                            break;
                        }
                        case 10007:{
                            ret_msg =@"用户已经存在";
                            break;
                        }
                            
                    }
                    if (![ret_msg isEqual:@"Success"]) {
                        [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                        return;
                    }else{
                        //注册成功
                        debugLog(@"%@",dict);
                        //保存用户数据
                        BOOL result = [[UserDao getInstance]saveUserData:dict];
                        NSArray *babyinfo = [dict objectForKey:@"babyinfo"];
                        if(babyinfo!=nil && babyinfo.count>0){
                            for (NSDictionary* dicc in babyinfo) {
                                [[BabyDao getInstance]saveBabyData:dicc];
                            }
                        }
                        if(result){
                            JoinClassViewController *joinClass = [[JoinClassViewController alloc]init];
                            [self.navigationController pushViewController:joinClass animated:YES];
                        }
                        
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                    return;
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                return;
            }
        }
        
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
